// * checkbox-group
<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
import Emitter from '../../mixins/emitter'
import { findComponentsDownward } from '../../utils/assist'

export default {
  name: 'CheckboxGroup',

  components: {},

  mixins: [Emitter],

  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {}
  },

  computed: {
    currentValue: {
      get() {
        return this.value
      },
      set(arr) {
        this.$emit('input', arr)
      },
    },
  },

  watch: {
    value() {
      this.updateModel()
    },
  },

  created() {},

  mounted() {},

  methods: {
    // * 数据更新
    updateModel() {
      // 对每一个子checkbox组件进行数据更新
      const children = findComponentsDownward(this, 'Checkbox')

      children.forEach(checkbox => (checkbox.model = this.value))
    },

    // * change事件-checkbox-group的model
    change(data) {
      this.currentValue = data

      this.notifyUserComponent({ type: 'change', data })

      this.notifyFormItem({ type: 'change', data })
    },

    // * 通知用户组件
    notifyUserComponent({ type, data }) {
      switch (type) {
        case 'change':
          this.$emit('on-change', data)
          break
      }
    },

    // * 通知FormItem组件
    notifyFormItem({ type, data }) {
      switch (type) {
        case 'change':
          this.dispatch('FormItem', 'on-form-change', data)
          break
      }
    },
  },
}
</script>
